use super::{json, Plc, RNull, SvCache, VBase, VMap};
use tracing::{instrument, warn};

#[instrument(skip_all, name = "list_mod")]
pub async fn do_gather(plc: &Plc, real: &SvCache, ckchange: bool) -> RNull {
    let cache_id = plc.get_cache_id()?;

    let change = plc.read_plc().await?;

    if ckchange {
        let mut is_change = false;

        if let Some(old) = real.get(&cache_id) {
            let old = old.ckobj()?;

            for (k, v) in change.iter() {
                is_change = match old.k_val(k) {
                    Some(val) => val != v,
                    None => true,
                };

                if is_change {
                    break;
                }
            }
        } else {
            is_change = true;
        }

        if !is_change {
            return Ok(());
        }
    }

    real.insert(cache_id, json!(change)).await;

    let tag = match plc.save_db(&change).await {
        Ok(_) => "wok",
        Err(e) => {
            warn!(target: "写入数据库", "error: {:?}", e);
            "wfail"
        }
    };

    if let Err(e) = plc.db_plc(tag).await {
        warn!(target: "数据库完成写入plc", "error: {:?}, {:?}", tag, e);
    }

    Ok(())
}
